package cc.vicp.djx314.starfood.web.personnel.dish;

import java.io.File;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import cc.vicp.djx314.starfood.util.FileUtil;
import cc.vicp.djx314.starfood.util.ImageIndex;

@Controller
public class DishImgUploadController {

	public final static Logger logger = LoggerFactory.getLogger(DishImgUploadController.class);

	@Autowired
	FileUtil fileUtil;

	@Autowired
	ImageIndex imageIndex;

	@RequestMapping(value = "/personnel/dish/dishimgupload", method = RequestMethod.POST)
	public ModelAndView headPortraitUploadTemp(
			@RequestParam(value = "jUploaderFile") CommonsMultipartFile mFile, HttpServletRequest request) {
		ModelAndView model = new ModelAndView("jsontournamenttemplate");
		ServletContext context = request.getSession().getServletContext();
		if (!mFile.isEmpty()) {
			String extend = fileUtil.getFileExtend(mFile.getOriginalFilename());
			String fileName = mFile.getOriginalFilename();
			logger.info("上传文件的名字：{}", fileName);
			String path = context.getRealPath("/img/dishimgtemp/");
			//获取本地存储路径
			File file = new File(path);
			if (!file.exists()) file.mkdirs();
			long name = new Date().getTime();
			//name +  + "." + extend;
			String saveName = new StringBuilder(name + "").append("-").append(imageIndex.getIndex())
					.append(".").append(extend).toString();
			File file1 = new File(path + "/" + saveName); // 新建一个文件
			try {
				mFile.getFileItem().write(file1); // 将上传的文件写入新建的文件中
				logger.info("=={}==文件上传成功，上传成功以后的文件名是=={}==", fileName, saveName);
				model.addObject("success", true);
				model.addObject("path", saveName);
			} catch (Exception e) {
				logger.error("文件上传失败", e);
				model.addObject("success", false);
			}
		} else {
			model.addObject("success", false);
		}
		return model;
	}
}